package com.aydx.remotevaluezookeeper.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.Watcher;

@Slf4j
public class CuratorTemplate {
    public CuratorTemplate(CuratorFramework curatorFramework) {
        this.curatorFramework = curatorFramework;
    }

    private CuratorFramework curatorFramework;

    public String getValue(String key, String defaultValue){
        try {
            byte[] data=this.curatorFramework.getData().forPath(key);
            if(data==null || data.length==0){
                return defaultValue;
            }
            return new String(data);
        } catch (Exception e) {
            log.error("ZookeeperTemplate.get",e);
        }
        return defaultValue;
    }
    public void addWatch(String key, Watcher watcher){
        try {
            this.curatorFramework.checkExists().usingWatcher(watcher).forPath(key);
        } catch (Exception e) {
            log.error("ZookeeperTemplate.addWatch",e);
        }
    }

    public void close(){
        this.curatorFramework.close();
        log.info("CuratorTemplate.closed.");
    }
    public CuratorFramework getCuratorFramework(){
        return this.curatorFramework;
    }
}
